import { defineStore } from 'pinia'
import { dialogInit } from './dialogInit'
import { uuid } from '@/utils/uuid'

export enum MessageType {
    TEXT = 1,
    AUDIO = 2,
    IMAGE = 3,
    VIDEO = 4
}

/**
 * 消息发送状态
 */
export enum SendStatus {
    PENDING = 0,    // 发送中
    SUCCESS = 1,    // 发送成功
    FAILED = 2      // 发送失败
}

export interface DialogItem {
    recordId: string,
    sendUserId: string,
    sendTime: number,
    type: MessageType,
    content: string,          // 文本内容或媒体文件的 URL
    isSelf: boolean,         // 是否为自己发送的消息
    status: SendStatus,      // 发送状态
    duration?: number        // 音频/视频时长（可选）
}



const useDialogStore = defineStore('dialog', () => {
    const messages = ref<DialogItem[]>(dialogInit())

    // 添加新消息
    const addMessage = (message: DialogItem): DialogItem => {
        messages.value.push(message)
        return message
    }

    const addMsg = ({ type, content ,duration}: { type: MessageType, content: string, duration?: number }): DialogItem => {
        const msg: DialogItem = {
            recordId: uuid(),
            sendUserId: '1',
            sendTime: Date.now(),
            type,
            content,  // 文本内容或媒体文件的 URL
            isSelf: true,         // 是否为自己发送的消息
            status: SendStatus.PENDING,      // 发送状态
            duration
        }
        return addMessage(msg)

    }

    const setStatus = (recordId: string, status: SendStatus) => {
        const message = messages.value.find(msg => msg.recordId === recordId)
        if (message) {
            message.status = status
        }
    }
    // 更新消息状态
    const updateMessageStatus = (recordId: string, status: SendStatus) => {
        const message = messages.value.find(msg => msg.recordId === recordId)
        if (message) {
            message.status = status
        }
    }

    // 获取所有消息
    const getAllMessages = computed(() => messages.value)

    // 清空消息
    const clearMessages = () => {
        messages.value = []
    }

    return {
        messages,
        getAllMessages,
        setStatus,
        addMessage,
        addMsg,
        updateMessageStatus,
        clearMessages
    }
}, {
    persist: true,
})

export default useDialogStore